from flask import Blueprint, request, abort, g, current_app
from flask_restful import Resource, Api, reqparse
from models import UserModel
from exts import db
import requests
import jwt
from datetime import datetime, timedelta, timezone
from config import WX_APP_ID, WX_APP_SECRET, SECRET_KEY
from decorators import login_required
from werkzeug.utils import secure_filename
import os

auth_api_bp = Blueprint('auth_api', __name__)
api = Api(auth_api_bp)

# 确保上传目录存在
UPLOAD_FOLDER = 'uploads/avatars'
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)

class WXLogin(Resource):
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('code', type=str, required=True, help='code is required')
        parser.add_argument('userInfo', type=dict, required=True, help='userInfo is required')
        args = parser.parse_args()
        
        url = 'https://api.weixin.qq.com/sns/jscode2session'
        params = {
            'appid': WX_APP_ID,
            'secret': WX_APP_SECRET,
            'js_code': args['code'],
            'grant_type': 'authorization_code'
        }
        
        response = requests.get(url, params=params)
        wx_data = response.json()
        
        if 'openid' not in wx_data:
            return {'message': 'Invalid code'}, 400
            
        openid = wx_data['openid']
        
        user = UserModel.query.filter_by(openid=openid).first()
        if not user:
            # 新用户，创建账号
            user_info = args['userInfo']
            user = UserModel(
                openid=openid,
                nickname=user_info.get('nickName'),
                avatar_url=user_info.get('avatarUrl'),
                gender=user_info.get('gender')
            )
            db.session.add(user)
            db.session.commit()
        
        token = jwt.encode({
            'user_id': user.id,
            'exp': datetime.now(timezone.utc) + timedelta(days=30)
        }, SECRET_KEY, algorithm='HS256')
        
        return {
            'token': token,
            'user_id': user.id,
            'userInfo': {
                'nickName': user.nickname,
                'avatarUrl': user.avatar_url,
                'gender': user.gender
            },
            'last_updated': user.updated_at.strftime('%Y-%m-%d %H:%M:%S')
        }

class UserStats(Resource):
    def get(self, user_id):
        user = UserModel.query.get(user_id)
        if not user:
            abort(404, message='User not found')
            
        return user.get_stats()

class UserProfileUpdate(Resource):
    @login_required
    def post(self):
        user = UserModel.query.get(g.user_id)
        if not user:
            return {'message': 'User not found'}, 404

        if 'avatar' in request.files:
            # 处理头像上传
            avatar_file = request.files['avatar']
            if avatar_file:
                # 安全地获取文件名
                filename = secure_filename(f"{user.id}_{datetime.now().strftime('%Y%m%d%H%M%S')}.png")
                # 保存文件
                filepath = os.path.join(UPLOAD_FOLDER, filename)
                avatar_file.save(filepath)
                
                # 更新用户头像URL
                avatar_url = f"/uploads/avatars/{filename}"
                user.avatar_url = avatar_url
                
                try:
                    db.session.commit()
                except Exception as e:
                    db.session.rollback()
                    return {'message': 'Database error'}, 500
                
                return {
                    'message': 'Avatar updated successfully',
                    'user': {
                        'id': user.id,
                        'nickname': user.nickname,
                        'avatar_url': avatar_url,
                        'last_updated': user.updated_at.strftime('%Y-%m-%d %H:%M:%S')
                    }
                }
        
        # 处理昵称更新
        data = request.get_json()
        if data and 'nickname' in data:
            user.nickname = data['nickname']
            try:
                db.session.commit()
            except Exception as e:
                db.session.rollback()
                return {'message': 'Database error'}, 500
        
        return {
            'message': 'Profile updated successfully',
            'user': {
                'id': user.id,
                'nickname': user.nickname,
                'avatar_url': user.avatar_url,
                'last_updated': user.updated_at.strftime('%Y-%m-%d %H:%M:%S')
            }
        }

api.add_resource(WXLogin, '/wx_login')
api.add_resource(UserStats, '/user/<int:user_id>/stats')
api.add_resource(UserProfileUpdate, '/user/profile/update')
